package com.example.weatherreport;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.weatherreport.db.DBManager;
import com.example.weatherreport.location.NowCityUtil;
import com.example.weatherreport.utils.SpUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;


public class MoreActivity extends AppCompatActivity implements View.OnClickListener{
    TextView bgTv,cacheTv,versionTv,shareTv,aiTV;
    RadioGroup exbgRg;
    ImageView backIv;
    private SharedPreferences pref;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);
        bgTv = findViewById(R.id.more_tv_exchangebg);
        cacheTv = findViewById(R.id.more_tv_cache);
        versionTv = findViewById(R.id.more_tv_version);
        shareTv = findViewById(R.id.more_tv_share);
        backIv = findViewById(R.id.more_iv_back);
        aiTV = findViewById(R.id.more_ai);
        exbgRg = findViewById(R.id.more_rg);
        bgTv.setOnClickListener(this);
        cacheTv.setOnClickListener(this);
        shareTv.setOnClickListener(this);
        backIv.setOnClickListener(this);
        aiTV.setOnClickListener(this);
        pref = getSharedPreferences("bg_pref", MODE_PRIVATE);
        String versionName = getVersionName();
        versionTv.setText("当前版本:    v"+versionName);
        setRGListener();
    }



    // 处理相册图片，放入缓存
    private static final int OPEN_GALLERY_REQUEST_CODE = 1;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        SharedPreferences.Editor editor = pref.edit();

        Intent intent = new Intent(MoreActivity.this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
            if (resultCode == Activity.RESULT_OK && data != null) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    //图片的序号
                    editor.putInt("bg", 99);
                    editor.commit();

                    SpUtils.saveDrawable(this,bitmap,"photo");

                    startActivity(intent);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
    }


    /* 设置改变背景图片的单选按钮的监听*/
    private void setRGListener() {
        exbgRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {//监听点击了哪个RadioGroup
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 获取目前的默认壁纸
                int bg = pref.getInt("bg", 0);
                SharedPreferences.Editor editor = pref.edit();
                Intent intent = new Intent(MoreActivity.this,MainActivity.class);//跳转到MainActivity
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                switch (checkedId) {
                    case R.id.more_rb_green:
                        if (bg==0) {
                            Toast.makeText(MoreActivity.this,"您选择的为当前背景，无需改变！",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        editor.putInt("bg",0);
                        editor.commit();
                        break;
                    case R.id.more_rb_pink:
                        if (bg==1) {
                            Toast.makeText(MoreActivity.this,"您选择的为当前背景，无需改变！",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        editor.putInt("bg",1);
                        editor.commit();
                        break;
                    case R.id.more_rb_blue:
                        if (bg==2) {
                            Toast.makeText(MoreActivity.this,"您选择的为当前背景，无需改变！",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        editor.putInt("bg",2);
                        editor.commit();
                        break;
                    //增加的项
                    case R.id.more_myself:
                        //用户可以换不同的壁纸，所以没有当前壁纸检测
                        //由于这个和另外几个的原理不同，不能startActivity在这里，否则就会出问题。
                        //去寻找是否已经有了权限
                        int a =  ContextCompat.checkSelfPermission(MoreActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                        //判断是否有读的权限，PERMISSION_GRANTED有权限，否则就是没有
                        // 请求权限的第一步是声明这个程序要能请求该权限，定义在AndroidManifest.xml内
                        if(ContextCompat.checkSelfPermission(MoreActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
                        {
                            //Intent调用选择器（只能选择图片）
                            //选择图片要调用外置存储，外置存储需要请求权限
                            Intent myintent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            //请求需要得到返回值，请求的Code = 1
                            //startActivityForResult的返回值需要在Activity内重写onActivityResult来接收传值

                            startActivityForResult(myintent, 1);
                            return;
                        }
                        else
                        {
                            //如果没有权限，请求对应的权限
                            ActivityCompat.requestPermissions(MoreActivity.this,new String[]{
                                    Manifest.permission.READ_EXTERNAL_STORAGE},1);
                            return;
                        }
                        //Toast.makeText(MainActivity.this,"您申请了动态权限",Toast.LENGTH_SHORT).show();
                        //自己选就不用估计上面bg是啥了
                        //另外：这里的选取值要去上面进行处理
                }
                startActivity(intent);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.more_iv_back:
                finish();   //返回
                break;
            case R.id.more_tv_cache:
                clearCache();   //清除缓存的函数
                break;
            case R.id.more_tv_share:
                shareSoftwareMsg("点击https://www.baidu.com/，下载天气预报app吧！");//分享内容
                break;
            case R.id.more_ai:
                goAi();//分享内容
                break;
            case R.id.more_tv_exchangebg:
                if (exbgRg.getVisibility() == View.VISIBLE) {   //点击切换”改变壁纸“菜单的显示和隐藏状态
                    exbgRg.setVisibility(View.GONE);
                }else{
                    exbgRg.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void goAi() {
        // 创建一个跳转意图，将当前Activity作为上下文，目标Activity.class作为参数
        Intent intent = new Intent(this, WenxinYanBackend.class);
        // 执行跳转
        startActivity(intent);
    }

    /*分享软件函数*/
    private void shareSoftwareMsg(String s) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,s);
        startActivity(Intent.createChooser(intent,"天气预报"));

    }

    private void clearCache() {
        /* 清除缓存的函数*/
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息").setMessage("确定要删除所有缓存么？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                NowCityUtil.clearNowCity();
                DBManager.deleteAllInfo();
                Toast.makeText(MoreActivity.this,"已清除全部缓存！",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MoreActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }).setNegativeButton("取消",null);
        builder.create().show();
    }

    public String getVersionName() {    // 获取的是 build.gradle 中的 versionName
        /* 获取应用的版本名称*/
        PackageManager manager = getPackageManager();
        String versionName = null;
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
